package com.mz.ieann.aide.base.vm

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.mz.ieann.dokit.utils.LogUtils

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2021 2021/11/14 11:57
 */
open class BaseVMAdapter<T, VD : ViewDataBinding>(
    private val itemList: List<T>?,
    @LayoutRes val layoutId: Int,
    private val br: Int
) : RecyclerView.Adapter<BaseVMAdapter<T, VD>.ViewHolder>() {

    private val resultList by lazy {
        if (itemList == null) ArrayList(0) else ArrayList<T>(itemList)
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        lateinit var binding: VD
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BaseVMAdapter<T, VD>.ViewHolder {
        val b = DataBindingUtil.inflate<VD>(
            LayoutInflater.from(parent.context),
            layoutId,
            parent,
            false
        )
        val holder = ViewHolder(b.root)
        holder.binding = b
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.setVariable(br, resultList[position])
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int {
        return resultList.size
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun setHasStableIds(hasStableIds: Boolean) {
        super.setHasStableIds(true)
    }

    /**
     * 获得选中的对象
     */
    open fun getBean(position : Int) : T {
        return resultList[position]
    }

    /**
     * 加载更多
     */
    fun onRefreshData(addList: List<T>?){
        if (addList.isNullOrEmpty()){
            LogUtils.e("add list can not bu null")
            return
        }
        runCatching {
            resultList.addAll(addList)
        }.onSuccess {
            notifyItemRangeChanged(itemCount, addList.size)
        }.onFailure {
            LogUtils.e("error: $it")
        }
    }

    /**
     * 清空原数据，用于下拉刷新
     */
    fun clearData(){
        notifyItemRangeRemoved(0, itemCount)
        resultList.clear()
    }

}